<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getComboDataApi1 } from "@/api/combo"
import { getComboDataDetailApi1 } from "@/api/combo/index1"
import { type IGetComboData } from "@/api/combo/types/combo"
import { ElMessage, type FormInstance } from "element-plus"
import { Search, Refresh } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { useComboSourceStore } from "@/store/modules/comboSource"
import { useTeamStore } from "@/store/modules/team"
import { useUserStore } from "@/store/modules/user"
import { Plus } from "@element-plus/icons-vue"
import { formatDateTime } from "@/utils"
import useClipboard from "vue-clipboard3"
import vueQr from "vue-qr/src/packages/vue-qr.vue"
const imageUrl = ref("")
/**地区数据 */
import { useCascaderAreaData } from "@vant/area-data"
const areaoptions = useCascaderAreaData()
defineOptions({
  name: "ProductList"
})
const activeName = ref("shelf")
const fileList = ref<any>([]) /**图片列表 */
const fileList1 = ref<any>([]) /**图片列表 */
const fileList2 = ref<any>([]) /**图片列表 */
const comboSourceStore = useComboSourceStore()
const teamStore = useTeamStore()
const userStore = useUserStore()
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

/** 产品来源数据获取 */
const comboSource = ref<any>([])
/**团队数据获取 */
const teamList = ref<any>([])

/**END */

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive<any>({
  name: "",
  source: "",
  sku: "",
  message: "",
  note: "",
  image: "",
  card: false,
  minAge: NaN,
  maxAge: NaN,
  area: [],
  state: "true"
})

const resetForm = () => {
  currentUpdateId.value = undefined
  clearValidate()
  formData.name = ""
  formData.source = ""
  formData.sku = ""
  formData.message = ""
  formData.note = ""
  formData.image = ""
  imageUrl.value = ""
  formData.card = false
  formData.area = []
  formData.maxAge = 0
  formData.minAge = 0
  fileList.value = []
  fileList1.value = []
  fileList2.value = []
  formData.state = "true"
}
//#endregion

//#endregion

const handleUpdate = (row: IGetComboData) => {
  loading.value = true
  currentUpdateId.value = row.id
  getComboDataDetailApi1({ id: row.id })
    .then((res: any) => {
      if (res.code == 200) {
        formData.name = res.data.name
        formData.source = res.data.source
        formData.sku = res.data.sku
        formData.message = res.data.message
        formData.note = res.data.note
        formData.card = res.data.card
        formData.minAge = res.data.minAge
        formData.maxAge = res.data.maxAge
        formData.superName = res.data.superName
        formData.packingRemark = res.data.packingRemark
        formData.superId = res.data.superId
        formData.team = res.data.team.split(",")
        formData.sum = res.data.sum
        formData.task = res.data.task
        formData.area = eval(res.data.area)
        formData.image = res.data.image?.split("/image/")[1]
        formData.img = res.data.img?.split("/image/")[1]
        if (res.data.image) {
          fileList.value = res.data.image?.split(",").map((item: any) => {
            return {
              url: item
            }
          })
        }

        if (res.data.img) {
          fileList2.value = res.data.img?.split(",").map((item: any) => {
            return {
              url: item
            }
          })
        }

        formData.imageList = res.data.imageList
          ?.split(",")
          .map((item: any) => {
            return item.split("/image/")[1]
          })
          .join()
        if (res.data.imageList) {
          fileList1.value = res.data.imageList
            .substring(0, res.data.imageList.length - 1)
            ?.split(",")
            .map((item: any) => {
              return {
                url: item
              }
            })
        }

        formData.state = res.data.state
        dialogVisible.value = true
      }
    })
    .finally(() => {
      loading.value = false
    })
  // selectedOptions.value = row.takeAddress.split("/")
}
//#region 改
const currentUpdateId = ref<undefined | string>(undefined)

//#endregion

//#region 查
const tableData = ref<IGetComboData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  state: "true",
  sku: "",
  id: "",
  team: userStore.teamName ? userStore.teamName : ""
})
const getTableData = () => {
  loading.value = true
  getComboDataApi1({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    state: searchData.state,
    team: searchData.team,
    name: searchData.name,
    id: searchData.id,
    sku: searchData.sku
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.packageList
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}

//#endregion
/**不发货地区多选 */
const props = {
  multiple: true,
  checkStrictly: true,
  label: "text",
  value: "text"
}
// 预览图片
const dialogImageUrl = ref("") /**预览url  */
const dialogVisible1 = ref(false) /**预览弹窗 */
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible1.value = true
}

/**分享产品 */
const dialogVisibleShare = ref<boolean>(false)
const link = ref<string>("")
const logoImg = ref<string>("")
const handleShare = (row: any) => {
  dialogVisibleShare.value = true
  link.value = `http://fansitexitong.cn/company/#/productDetil?p=${row.id}&u=${userStore.usernameID}`
  logoImg.value = row.imageList.split(",")[0]
  // link.value = `http://192.168.1.7:3336/#/productDetil?p=${row.id}&u=${userStore.usernameID}`
}
const { toClipboard } = useClipboard()
const copy = async (text: string) => {
  try {
    await toClipboard(text) //实现复制
    ElMessage.success("已复制产品链接！")
  } catch (e) {
    console.error(e)
  }
}
/**tab 切换 */
const handleClick = (tab: any) => {
  if (tab.paneName === "shelf") {
    searchData.state = "true"
  } else {
    searchData.state = "false"
  }
  getTableData()
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
/**监听comboSource缓存 */
comboSourceStore.getCsourceFn()
watch(
  [() => comboSourceStore.comboSourceListStore],
  (newValue) => {
    comboSource.value = newValue.flat()
  },
  {
    immediate: true
  }
)
/**comboSource END */
/**监听 team 缓存 */
teamStore.getTeamFn()
watch(
  [() => teamStore.teamListStore],
  (newValue) => {
    teamList.value = newValue.flat()
  },
  {
    immediate: true
  }
)
/**team END */
// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
}
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="id" label="Id查询">
          <el-input v-model.trim="searchData.id" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="name" label="产品名">
          <el-input v-model.trim="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="sku" label="产品编码" v-if="!userStore.teamName">
          <el-input v-model.trim="searchData.sku" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="table-wrapper">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="在售产品" name="shelf" />
          <el-tab-pane label="已下架产品" name="offShelf" />
        </el-tabs>

        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="image" label="产品主图" align="center">
            <template #default="scope">
              <img :src="scope.row.imageList.split(',')[0]" alt="" width="80" height="80" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="产品名" align="center" />
          <!-- <el-table-column prop="message" label="产品详情" align="center" show-overflow-tooltip /> -->
          <!-- <el-table-column prop="note" label="产品备注" align="center" show-overflow-tooltip /> -->
          <el-table-column prop="date" label="发布时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.date) }}
            </template>
          </el-table-column>
          <el-table-column prop="update" label="更新时间" align="center">
            <template #default="scope">
              <span v-if="scope.row.update">{{ formatDateTime(scope.row.update) }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="280" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">查看详情</el-button>
              <el-button style="display: none" type="primary" text bg size="small" @click="handleShare(scope.row)"
                >分享产品</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增产品' : '查看产品'"
      @close="resetForm"
      width="80%"
    >
      <el-form ref="formRef" :model="formData" label-width="100px" label-position="left">
        <el-form-item prop="name" label="产品名">
          <el-input v-model="formData.name" disabled />
        </el-form-item>
        <el-form-item prop="sku" label="产品编码">
          <el-input v-model="formData.sku" disabled />
        </el-form-item>
        <el-form-item prop="packingRemark" label="包装备注">
          <el-input v-model="formData.packingRemark" placeholder="请输入" type="textarea" disabled />
        </el-form-item>
        <el-form-item prop="message" label="产品详情">
          <!-- <el-input v-model="formData.message" type="textarea" autosize disabled /> -->
          <!-- <Editor :value="formData.message" @updateValue="getMsg"  /> -->
          <div v-html="formData.message" style="height: 300px; width: 100%; overflow-y: auto" class="overflowBpx" />
        </el-form-item>
        <!-- <el-form-item prop="note" label="产品备注">
          <el-input v-model="formData.note" type="textarea" autosize disabled />
        </el-form-item> -->
        <el-form-item prop="card" label="上传身份证">
          <el-select v-model="formData.card" clearable disabled style="width: 240px">
            <el-option :key="1" label="是" :value="true" />
            <el-option :key="2" label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item prop="age" label="年龄限制" class="ageInput">
          <el-input
            type="number"
            disabled
            v-model="formData.minAge"
            oninput="if(value.length>2)value=value.slice(0, 2)"
          />
          <span style="display: inline-block; padding: 0 5px">至</span>
          <el-input
            type="number"
            disabled
            v-model="formData.maxAge"
            oninput="if(value.length>2)value=value.slice(0, 2)"
          />
        </el-form-item>
        <el-form-item prop="area" label="不发货地区">
          <el-cascader size="large" disabled :props="props" :options="areaoptions" v-model="formData.area" />
        </el-form-item>
        <el-form-item prop="team" label="可销售团队" style="display: none">
          <el-select v-model="formData.team" clearable multiple style="width: 240px" disabled>
            <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="sum"
          label="佣金规则T1金额"
          v-if="
            userStore.roles.join() !== '文员' &&
            userStore.roles.join() !== '售后客服' &&
            userStore.roles.join() !== '外部分销' &&
            userStore.roles.join() !== '拼多多文员' &&
            userStore.roles.join() !== '天猫平台文员' &&
            userStore.roles.join() !== '京东平台文员' &&
            userStore.roles.join() !== '抖音小店文员' &&
            userStore.roles.join() !== '新媒体-业务员'
          "
        >
          <el-input v-model="formData.sum" disabled />
        </el-form-item>
        <el-form-item prop="task" label="任务量规则">
          <el-input v-model="formData.task" disabled type="textarea" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="image" label="产品主图">
          <el-upload
            :auto-upload="false"
            :file-list="fileList1"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            disabled
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item prop="image" label="详情图">
          <el-upload
            :auto-upload="false"
            :file-list="fileList"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            disabled
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item prop="image" label="H5背景图">
          <el-upload
            :auto-upload="false"
            :file-list="fileList2"
            :show-file-list="true"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            disabled
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-model="dialogVisibleShare" title="分享产品" width="50%">
      <div>
        <span>产品链接：</span>
        <el-link>{{ link }}</el-link>
        <el-link type="primary" style="margin-left: 10px" @click="copy(link)"
          ><el-icon><DocumentCopy /></el-icon>复制</el-link
        >
      </div>
      <div style="margin-top: 30px">
        <span style="vertical-align: top">产品二维码：</span>
        <vue-qr :text="link" :size="200" />
      </div>
    </el-dialog>
    <el-dialog v-model="dialogVisible1">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.ageInput :deep(.el-input) {
  width: 45% !important;
}
:deep(.el-form-item__label) {
  width: 130px !important;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
:deep(.el-cascader) {
  width: 567px !important;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.overflowBpx {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 0 20px 0 20px;
}
</style>
